package com.zb;

import com.zb.eneity.Server;
import com.zb.eneity.Tenant;
import com.zb.mapper.ServerMapper;
import com.zb.mapper.TenantMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigInteger;

/**
 * 对外暴露出去 需要根据哪个租户Id来切换数据源
 *      比如可以在登录拦截器中调用这个组件 用来设置整体的上下文
 */
@Slf4j
@Component
public class ActiveTenantDataSourceComp {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private ServerMapper serverMapper;

    public void activeTenantDataSource(BigInteger tenantId) {
        Tenant tenant = tenantMapper.selectById(tenantId);
        Assert.notNull(tenant,"tenantId is not found Tenant!!!");

        Server server = serverMapper.selectById(tenant.getServerId());
        Assert.notNull(server,"serverId is not found Server!!!");
        TenantContextHolder.setTenantId(tenantId);
        TenantContextHolder.setDataSource(server.getDbName());

        log.info("当前线程上下文租户Id tenantId:{},对应服务器信息:{}",tenantId,server);
    }
}
